<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="default" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="任务名称" prop="jobName">
        <el-input
          v-model="queryParams.jobName"
          placeholder="请输入任务名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="任务组名" prop="jobGroup">
        <el-select
          v-model="queryParams.jobGroup"
          placeholder="请选择任务组名"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in sys_job_group"
            :key="dict.dataValue"
            :label="dict.dataName"
            :value="dict.dataValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="执行状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择执行状态"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in sys_common_status"
            :key="dict.dataValue"
            :label="dict.dataName"
            :value="dict.dataValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="执行时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button plain icon="Search" type="primary" size="default" @click="handleQuery">搜索</el-button>
        <el-button plain icon="Refresh" size="default" @click="resetQuery(queryForm)">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          size="default"
          :disabled="multiple"
          @click="handleDelete"
          v-if="userStore.hasPermission('monitor:jobLog:remove')"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          size="default"
          @click="handleClean"
          v-if="userStore.hasPermission('monitor:jobLog:remove')"
        >清空</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          size="default"
          @click="handleExport"
          v-if="userStore.hasPermission('monitor:jobLog:export')"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Close"
          size="default"
          @click="handleClose"
        >关闭</el-button>
      </el-col>
    </el-row>

    <el-table style="font-size: 16px;" v-loading="loading" :data="jobLogList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="日志编号" width="80" align="center" prop="jobLogId" />
      <el-table-column label="任务名称" align="center" prop="jobName" :show-overflow-tooltip="true" />
      <el-table-column label="任务组名" align="center" prop="jobGroup" :show-overflow-tooltip="true">
        <template   #default="scope">
          <div v-for="item in sys_job_group">
            <span  v-if="scope.row.jobGroup == item.dataValue">{{item.dataName}}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="调用目标字符串" align="center" prop="invokeTarget" :show-overflow-tooltip="true" />
      <el-table-column label="日志信息" align="center" prop="jobMessage" :show-overflow-tooltip="true" />
      <el-table-column label="执行状态" align="center" prop="status">
        <template   #default="scope">
          <div v-for="item in sys_common_status">
            <span  v-if="scope.row.status == item.dataValue">{{item.dataName}}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="执行时间" align="center" prop="createTime" width="180">
        <template   #default="scope">
          <span>{{ formatTimestamp(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template   #default="scope">
          <el-button
            size="default"
            type="text"
            plain
            icon="View"
            @click="handleView(scope.row)"
            v-if="userStore.hasPermission('monitor:jobLog:query')"
          >详细</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="el-pager">
      <el-pagination layout="total,sizes,prev, pager, next,jumper" :total="total"
                     :page-sizes="[10,20,30,40,50]" :pager-count="11"
                     size="default"  background  class="mt-4" :current-page="currentPage"
                     @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
    </div>

    <!-- 调度日志详细 -->
    <el-dialog title="调度日志详细" v-model="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" label-width="100px" size="mini">
        <el-row>
          <el-col :span="12">
            <el-form-item label="日志序号：">{{ form.jobLogId }}</el-form-item>
            <el-form-item label="任务名称：">{{ form.jobName }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务分组：">{{ form.jobGroup }}</el-form-item>
            <el-form-item label="执行时间：">{{ formatTimestamp(form.createTime) }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="调用方法：">{{ form.invokeTarget }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="日志信息：">{{ form.jobMessage }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="执行状态：">
              <div v-if="form.status == 0">正常</div>
              <div v-else-if="form.status == 1">失败</div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="异常信息：" v-if="form.status == 1">{{ form.exceptionInfo }}</el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="open = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { info} from "@/api/monitor/job";
import { page, remove, cleanJobLog } from "@/api/monitor/jobLog";
import {useRouteStore} from "@/stores/route.ts";
import {onMounted, reactive, ref, watchEffect} from "vue";
import {ElMessage, ElMessageBox, type FormInstance} from "element-plus";
import {formatTimestamp} from "@/utils/date";
import {useUserStore} from "@/stores/user.ts";
const userStore = useUserStore()
const useStore = useRouteStore();
const route = useStore.route;
const loading=ref(true)
const ids=ref([])
const multiple=ref(true)
const showSearch=ref(true)
const total=ref(0)
const jobLogList=ref([])
const open=ref(false)
const dateRange=ref([])
const queryForm=ref<FormInstance>();
const form=reactive({
  jobLogId:null,
  jobName:'',
  jobGroup:'',
  createTime:null,
  invokeTarget:'',
  jobMessage:'',
  status:''
})
const sys_job_group=userStore.getDictData('sys_job_group');
const sys_common_status=userStore.getDictData('sys_common_status');
const queryParams=ref({
  page: 1,
  limit: 10,
  jobName: undefined,
  jobGroup: undefined,
  status: undefined
})
watchEffect(()=> {
  const jobId = route.params.jobId;
  if (jobId !== undefined && jobId != 0) {
    info(jobId).then(response => {
      queryParams.value.jobName = response.data.jobName;
      queryParams.value.jobGroup = response.data.jobGroup;
      getList();
    });
  } else {
    getList();
  }
})
onMounted(()=>{
  const jobId = route.params.jobId;
  if (jobId !== undefined && jobId != 0) {
    info(jobId).then(response => {
      queryParams.value.jobName = response.data.jobName;
      queryParams.value.jobGroup = response.data.jobGroup;
      getList();
    });
  } else {
    getList();
  }
})
/** 查询调度日志列表 */
const getList=()=> {
  loading.value = true;
  page(queryParams.value).then(response => {
        jobLogList.value = response.data.list;
        total.value = response.data.total;
        loading.value = false;
      }
  );
}

const currentPage = ref(1)
const handleSizeChange = (val: number) => {
  queryParams.value.limit= val;
  getList();
}
const handleCurrentChange = (val: number) => {
  currentPage.value= val;
  queryParams.value.page= val;
  getList();
}

// 返回按钮
const handleClose=()=> {
  // const obj = { path: "/monitor/job" };
  window.history.back();
}
/** 搜索按钮操作 */
const handleQuery=()=> {
  queryParams.value.page = 1;
  getList();
}
const resetQuery = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  handleQuery();
}
// 多选框选中数据
const handleSelectionChange=(selection)=> {
  ids.value = selection.map(item => item.jobLogId);
  multiple.value = !selection.length;
}
/** 详细按钮操作 */
const handleView=(row)=> {
  open.value = true;
  form.jobLogId=row.jobLogId;
  form.jobName=row.jobName;
  form.jobGroup=row.jobGroup;
  form.createTime=row.createTime;
  form.invokeTarget=row.invokeTarget;
  form.jobMessage=row.jobMessage;
  form.status=row.status;
}
/** 删除按钮操作 */
const handleDelete=(row)=> {
  const jobLogIds = ids.value;
  ElMessageBox.confirm('是否确认删除调度日志编号为"' + jobLogIds + '"的数据项？','提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
  })
      .then(async ({ value }) =>  {
        await remove(jobLogIds)
        getList();
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
        return true;
      })
      .catch(() => {
      })
}
/** 清空按钮操作 */
const handleClean=()=> {
  ElMessageBox.confirm('是否确认清空所有调度日志数据项？','提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
  })
  .then(({ value }) =>  {
    cleanJobLog().then(res=>{
      getList();
      ElMessage({
        type: 'success',
        message: '清空成功',
      })
    })
  })
  .catch(() => {
  })
}
/** 导出按钮操作 */
const handleExport=()=> {
  this.download('/monitor/jobLog/export', {
    ...this.queryParams
  }, `log_${new Date().getTime()}.xlsx`)
}
</script>
